package com.sbm.datasource.dynamic;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Order(-10)
@Component
public class DynamicDataSourceAspect {
    @Autowired
    private DynamicDataSourceSwitcher switcher;

    @Pointcut("@annotation(com.sbm.datasource.dynamic.DynamicDataSourceTarget)")
    public void DynamicDataSourceTargetPointcut() {
    }

    @Before(value = "DynamicDataSourceTargetPointcut()", argNames = "target")
    public void switchDataSource(JoinPoint joinPoint) {
        this.switcher.switchTo(joinPoint);
    }

    @After(value = "DynamicDataSourceTargetPointcut()")
    public void resetDataSource(JoinPoint joinPoint) {
        this.switcher.backFrom(joinPoint);
    }

}
